package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.exception.DisableException;
import com.itheima.exception.RepeatException;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    /*请求url地址： /employee/login
    请求方式：POST
    请求参数：json格式*/
    //后台登录系统
    @Autowired
    EmployeeService employeeService;

    @PostMapping("/login")
    public R empLogin(HttpServletRequest request,@RequestBody Employee employee){
        //创建条件构造器
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        //根据传入的name进行判断
        wrapper.lambda().eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(wrapper);
        if(one==null){
            return R.error("登录失败");
        }

        String password  = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!one.getPassword().equals(password)){
            return R.error("登录失败");
        }

        if(one.getStatus() == 0){
            return R.error("账号已禁用");
        }
        request.getSession().setAttribute("employee",one);
        return R.success(one);
    }

    /*请求url地址： /employee/logout
    请求方式：POST
    请求参数：无
    响应结果【格式统一】：*/
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /*
    添加员工
    请求url地址： /employee
    请求方式：POST
    请求参数：json格式   后台使用Employee实体类接收*/
    @PostMapping
    public R sava(HttpServletRequest request,@RequestBody Employee employee){
        /*Employee attribute = (Employee) request.getSession().getAttribute("employee");

        Long o = attribute.getId();*/

        //判断注册员工在数据库中是否重复
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(wrapper);
        if(one!=null){
            throw new RepeatException("用户已存在");
        }
        //开始添加用户
        //密码加密
        String s1 = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(s1);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(ThreadCommon.getTableLogic());
//        employee.setCreateUser(ThreadCommon.getTableLogic());
        employeeService.save(employee);
        return R.success("employee");
    }

    /*mybatisplus:默认提供的分页对象page
    records
    total
    请求url地址： /employee/page      ? page=1&pageSize=10&name=zs
    请求方式：GET
    请求参数：?page=1&pageSize=10&name=zs*/
    @GetMapping("/page")
    public R selectPage(int page,int pageSize,String name){
        if(name!=null){
            QueryWrapper<Employee> wrapper = new QueryWrapper<>();
            wrapper.lambda().like(name!=null&&name!="",Employee::getName,name);
            IPage iPage = employeeService.pageMaps(new Page<>(page,pageSize), wrapper);
            return R.success(iPage);
        }else {
            return R.success(employeeService.page(new Page<>(page,pageSize)));
        }

    }

    /*请求url地址： /employee
    请求方式：PUT
    请求参数：JSON    使用Employee对象接收
    响应结果【格式统一】：R 对象
    return  R.success("修改成功")*/
    @PutMapping
    public R delete(HttpServletRequest request,@RequestBody Employee employee) {
        //判断账号是否是管理员账号
        //Employee emp = (Employee) request.getSession().getAttribute("employee");
        //Long id = employee.getId();

       /* if(id==emp.getId()){
           throw new DisableException("管理员无法禁用自己");
        }*/
        if(employee.getId()==1l){
            throw new DisableException("管理员无法禁用自己");
        }
        //给修改人员字段赋值
//        employee.setUpdateUser(ThreadCommon.getTableLogic());

        //更改表中数据操作时间
//        employee.setUpdateTime(LocalDateTime.now());

        //获取需要修改的id
        employeeService.updateById(employee);

        return R.success("employee");
    }

    /*接口一：根据id查询员工【用于编辑窗口的数据回显】
    请求url地址： /employee/1503342331818840066
    请求方式：GET
    请求参数：无     url传参
    响应结果【格式统一】：R
    "code":  0 失败  1 成功,
    "data":{ 员工对象数据 },  // Employee
    "msg":null
    */
    //根据id查找员工信息
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        //判断id在数据库中是否存在
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Employee::getId,id);
        Employee one = employeeService.getOne(wrapper);
        if(one==null){
            return R.error("用户不存在");
        }
        return R.success(one);
    }


}
